﻿using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace WebApp
{

    //2.1.0-rc1-final 才可以引入BackgroundService类,
    public class MyHostedService2 : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine("MyHostedService2 is starting.");

            stoppingToken.Register(() => Console.WriteLine("MyHostedService2 is stopping."));

            while (!stoppingToken.IsCancellationRequested)
            {
                Console.WriteLine("MyHostedService2 is doing background work.");

                await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
            }

            Console.WriteLine("MyHostedService2 background task is stopping.");
        }
    }

    public class MyHostedService : IHostedService
    {
        private CancellationTokenSource _cts;
        private Task _executeTask;

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            _executeTask = Task.Run(async () =>
           {
               while (!_cts.IsCancellationRequested)
               {
                   Console.WriteLine("MyHostedService service run.");
                   await Task.Delay(5000);
               }

           });
            return Task.CompletedTask;
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            _cts.Cancel();
            //await Task.Delay(-1, cancellationToken);
            await Task.WhenAny(_executeTask);
            Console.WriteLine("MyHostedService stop.");
            cancellationToken.ThrowIfCancellationRequested();
        }
    }
}
